package view.microgui
{
	import flash.display.Sprite;
	import flash.utils.Dictionary;
	import model.micro.FieldUnit;
	import view.micro.FieldUnitSprite;
	import view.micro.IMicroSprite;
	
	/**
	 */
	public class AttackIconManager extends Sprite implements IMicroSprite
	{
		
		private var icons:Vector.<AttackSelectorIcon>;
		private var icon_map:Dictionary;
		
		public function AttackIconManager()
		{
			icons = new Vector.<AttackSelectorIcon>();
			icon_map = new Dictionary();
		}
		
		public function update():void
		{
			graphics.clear();
			icons = icons.sort(function(a:AttackSelectorIcon, b:AttackSelectorIcon):int
			{
				var diff = a.unit_sprite.x - b.unit_sprite.x;
				if (Math.abs(diff) < 1.0) {
					return icons.indexOf(a) - icons.indexOf(b);
				} else {
					return diff;
				}
			});
		
			for (var i:int = icons.length - 1; i >= 0; i--)
			{
				var icon:AttackSelectorIcon = icons[i];
				if (icon.readyToRemove())
				{
					removeChild(icon);
					icon_map[icon.unit_sprite.unit] = null;
					icons.splice(i, 1);
				}
				else
				{
					icon.update();
					
					icon.y = 180;
					if (i < icons.length - 1) {
						var other = icons[i + 1];
						if (other.x - icon.x < 30) {
							var w = Math.pow(Math.abs(icon.x - other.x) / 30, 4);
							icon.y += (1 - w) * (other.y - icon.y + icon.radius + other.radius + 5);
						}
					}
					
					if ((icon.unit_sprite.unit.controller.target as FieldUnit) != null)
					{
						var target:AttackSelectorIcon = icon_map[icon.unit_sprite.unit.controller.target];
						if (target != null)
						{
							graphics.lineStyle(0, icon.unit_sprite.unit.macroUnit.owner.color);
							graphics.moveTo(icon.x, icon.y);
							if (icon.unit_sprite.unit.macroUnit.owner.color == 0x0000FF)
							{ // TODO: Find a real way to check which team
								graphics.curveTo((icon.x + target.x) / 2, (target.y + icon.y) / 2 - 40, target.x, target.y);
							}
							else
							{
								graphics.curveTo((icon.x + target.x) / 2, (target.y + icon.y) / 2 + 40, target.x, target.y);
							}
							graphics.lineStyle();
						}
					}
				}
			}
		}
		
		public function readyToRemove():Boolean
		{
			return false;
		}
		
		public function addUnit(unit_sprite:FieldUnitSprite):void
		{
			var icon:AttackSelectorIcon = new AttackSelectorIcon(unit_sprite);
			addChild(icon);
			icons.push(icon);
			icon_map[unit_sprite.unit] = icon;
		}
	
	}

}